<!DOCTYPE html>
<html>
<head>
	<title>主页</title>
	<meta charset="utf-8" />
    <meta name="viewport" content="width = device-width , initial-scale = 1 , minimum-scale = 1 , maximum-scale = 1">
	<link rel="stylesheet" href="resource/css/bootstrap.min.css">
    <link rel="stylesheet" href="resource/css/common.css">
	<link rel="stylesheet" type="text/css" media="screen" href="resource/css/style.css">
<!--    <link rel="stylesheet" type="text/css" media="screen" href="style.css">-->
</head>
<body>
<!------------------页头------------------------------------>
<div id="header">
    <a href="webpage/index/city.html" class="to_position"></a>
    <h1>优惠广场</h1>
    <a class="index_login" onclick="judgeLogin()">&#xe6e4;</a>
    <a class="index_search" onclick="linkToSearch()">&#xe62b;</a>
</div>
<!------------------轮播------------------------------------>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
        <li data-target="#carousel-example-generic" data-slide-to="3"></li>
    </ol>
    <div class="carousel-inner" role="listbox">
        <div class="item active"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
</div>
<!------------------积分商城----------------------------------->
<div class="jifen_store">
    <div class="listSelect">
        <div onclick="showShopCoupon()">商家优惠</div>
        <div onclick="showUserCoupon()">个人发布</div>
        <div onclick="linkToCouponShop()">积分商城</div>
    </div>
    <div class="jifen_shops"></div>
    <div class="user_coupon"></div>
</div>
<div class="no_more"></div>



<!--模态框 start-->
<div class="modal fade position_change" id="myModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body"></div>
            <div class="modal-footer">
                <button type="button" class="sanFast-btn"
                        data-dismiss="modal">返回
                </button>
                <button type="button" class="sanFast-btn release">
                    去登录
                </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade position_change" id="Modal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body"></div>
            <div class="modal-footer">
                <button type="button" class="sanFast-btn"
                        data-dismiss="modal">返回
                </button>
            </div>
        </div>
    </div>
</div>
<!--模态框 end-->
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="resource/js/jquery.min.js"></script>

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="resource/js/bootstrap.min.js"></script>
<script src="resource/js/hammer.min.js"></script>
<script src="resource/js/jquery.hammer.js"></script>
<script src="resource/js/commonjs.js"></script>
<script src="resource/js/ReceiveAndConvert.js"></script>
<script src="http://api.map.baidu.com/api?v=2.0&ak=qVrWQw9Vs8t7iPfG7bSj0137" type="text/javascript"></script>
<script>
    var longitude = null;
    var latitude = null;
    var page = null,page_2=null;  //页数
    var no = null,num=null;  //每页条数
    var allLoad = null,allLoad_2=null;//判断是否加载完毕
    var isFirstTime = null,isFirstTime2=null;//判断是否为第一次加载
    var loadControl = null,loadControl_2=null;//控制每次只加载一下
    var data_size=null,size=null;
    var flag=false;
    $(function() {
        $('#carousel-example-generic').hammer().on('swipeleft', function(){
            $(this).carousel('next');
            $(this).carousel({interval: 1000});
        });

        $('#carousel-example-generic').hammer().on('swiperight', function(){
            $(this).carousel('prev');
            $(this).carousel({interval: 1000});
        });
        init();
    });
    function init(){
        /*banner*/
        var url = "/Home/getBanner";
        var arg = {};
        ajaxJsonp(url, arg, getBanner);

        /*position city*/
        var city_name = getCookie("city");
        if(city_name==undefined){
            var myCity = new BMap.LocalCity();
            myCity.get(getPosition);
        }else{
            if(city_name.length<=3){
                var city_name_1 = city_name;
            }else if(city_name.length>3){
                var city_name_1 = city_name.substr(0,3)+"..";
            }
            $(".to_position").append("<span>"+city_name_1+"</span>");
            $(".to_position").append("<span>&#xe626;</span>");
            $(".position_city").text(city_name_1);
        }
        /*user image*/
        getUserImage();

        /*loading shops*/
        get_lonAndLat();
        showShopCoupon();
    }
    /*页面的跳转*/
    function linkToSearch() {
        location.href = "webpage/index/search_coupon.html?url=1";
    }
    function linkToCouponShop(){
        window.location.href = "webpage/integralMall/integral_index.html?url=1";
    }
    function linkToSellDetail(shop_id){
        window.location.href = "webpage/index/sellerDetail.html?shop_id=" + shop_id;
    }
    /*首页banner的获取*/
    function getBanner(res){
        var imgSrcList=new Array();
        for(var i=0;i<res.data.length;i++){
            var img_src=res.data[i].image;
            var img_url=res.data[i].url;
            var add_img='<a href="'+img_url+'"><img src='+img_src+'></a>';
            imgSrcList.push(add_img);
        }
        setTimeout(function(){
            $(".carousel-indicators").show();
        },500);
        $(".carousel-inner .item").each(function(index,obj){
            $(obj).append(imgSrcList[index]);
        });
        $(".jifen_store").append("<div class='load-more' style='margin-top: 20%;'><img src='resource/images/loading.jpg'/></div>");
    }
    /*获取定位的城市*/
    function getPosition(result) {
        var cityName = result.name;
        saveCookie("city", cityName, 20, "path=/");
        if(cityName.length<=3){
            var cityName_1 = cityName;
        }else if(cityName.length>3){
            var cityName_1 = cityName.substr(0,3)+"..";
        }
        $(".to_position").append("<span>"+cityName_1+"</span>");
        $(".to_position").append("<span>&#xe626;</span>");
        setTimeout(function(){
            var msg= '<div>'+
                    '<span> 您当前位置为</span>'+
                    '<span class="position_city">成都</span><br>'+
                    '<div>';
            $('#myModal .modal-body').text(" ");
            $('#myModal .modal-body').append(msg);
            $("#myModal .modal-footer button:nth-of-type(1)").text("切换");
            $("#myModal .modal-footer button:nth-of-type(2)").text("是");
            $('#myModal').modal();
            $("#myModal .modal-footer button:nth-of-type(1)").click(function(){
                window.location.href = "webpage/index/city.html?url=1";
            })
            $("#myModal .modal-footer button:nth-of-type(2)").click(function(){
                $('#myModal').modal("hide");
            })
        },1000)
    }
    /*获取用户是否登录，改变头像,提示信息弹框*/
    function getUserImage(){
        var token = getCookie("token");
        if(token != -1 && token != undefined){
            var url = "/UserCenter/getUserDetail";
            var arg = {};
            ajaxJsonp(url, arg, addUserImage, "get");
        }
    }
    function addUserImage(res){
        var code=res.status.code;
        if(code==1){
            var userImage=res.data.user_info.avatar;
            $(".index_login").text("");
            if(userImage==null){
                $(".index_login").append('<img src="resource/images/user_gray.png">');
            }else{
                $(".index_login").append('<img src="'+userImage+'">');
            }
        }
    }

    /*点击头像，判断是否登录，登录后跳转用户中心，未登录提示登录*/
    function judgeLogin(){
        var token = getCookie("token");
        if(token==null||token==-1||token==undefined){
            location.href="webpage/login/login.html?url=1";
        }else{
            window.location.href = "webpage/userInfo/userInfo.html?url=1";
        }
    }

    function showShopCoupon(){
        $(".jifen_shops").show();
        $(".listSelect div:nth-of-type(1)").addClass("active");
        $(".listSelect div:nth-of-type(2)").removeClass("active");
        $(".user_coupon").hide();
        $(".no_more").hide();
        loadMoreCouponBind();
    }
    function showUserCoupon(){
        $(".user_coupon").show();
        $(".listSelect div:nth-of-type(1)").removeClass("active");
        $(".listSelect div:nth-of-type(2)").addClass("active");
        $(".jifen_shops").hide();
        $(".no_more").hide();
        if(flag==false){
            $(".load-more").show();
            get_address();
            loadMoreCouponBind_2();
        }
        flag=true;
    }
    /*根据位置来显示首页上的商家优惠券*/
    function get_lonAndLat() {    //当前位置的经纬度
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                longitude = r.point.lng;
                latitude = r.point.lat;
                page=1;
                no=3;
                loadingShops();
            }
            else {
                alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true})
    }
    function loadingShops(){
        var url = "/Home/getShopList";
        var arg = {};
        arg.lon=longitude;
        arg.lat=latitude;
        arg.page=page;
        arg.no=no;
        ajaxJsonp(url, arg, getShops);
    }

    function getShops(res) {
        var data = res.data.list;
        data_size=res.data.count;
        if(data_size==0){
            $(".jifen_shops").append('<div class="noCouponResult">该地区没有优惠券信息！</div>');
            $(".load-more").hide();
        }else{
            for (var j = 0; j < data.length; j++) {
                var shop_id = data[j].shop_id;
                var shop_name = data[j].shop_name;
                var image = data[j].image;
                var business_name = data[j].business_name;
                var discount = data[j].discount;
                var coupon_id = data[j].coupon_id;
                var start_time = data[j].start_time;  //开始时间
                var expired_time = data[j].expired_time;  //结束时间
                var credit=data[j].credit;
                var start_time1=timeChange(start_time).substr(2, 7);
                var expired_time1=timeChange(expired_time).substr(2, 7);
                var coupon_count = data[j].coupon_count;
                var for_count = data[j].for_count;  //表示剩余的数量
                var percent = (for_count / coupon_count) * 100;  //计算未领取的数量的百分比
                var juli_1= data[j].juli;    //距离
                var juli=null;
                if(juli_1<1){
                    juli=juli_1.substr(2, 4)*1000+"m";
                }else if(juli_1>=1){
                    juli=juli_1.substr(0, 4)+"km";
                }
                var labelList=data[j].label_list;
                var shop_couponList_1='' +
                        '<div class="index_stores" onclick="linkToSellDetail('+shop_id+')">' +
                        '<div class="store_detail">'+
                        '<div><label class="label_8">'+discount+'</label><img src='+image+'></div>'+
                        '<ul>'+
                        '<li><a><span>'+business_name+'</span><span>('+shop_name+')</span></a></li>'+
                        '<li class="'+shop_id+'">'+
                            '<span data-id="'+labelList[0].id+'">'+labelList[0].name+'</span>'+'  '+
                            '<span data-id="'+labelList[1].id+'">'+labelList[1].name+'</span>'+'  '+
                            '<span>'+labelList[2]+'</span>'+'  '+
                            '<span>'+labelList[3]+'</span>'+
                        '</li>'+
                        '<li>'+juli+'</li>'+
                        '<li>'+start_time1+'-'+expired_time1+'</li>'+
                        '</ul>'+
                        '</div>'+
                        '<div class="pinjia">'+
                        '<div class="discuss">'+
                        '<div class="progress">'+
                        '<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:'+percent+'%;"></div>'+
                        '</div>'+
                        '<label class="number"> <span class="numberOne">'+for_count+'</span><span style="margin-left: 10px;">'+coupon_count+'</span></label>'+
                        '</div>'
                if(credit==0){
                    var shop_couponList_2='<p class='+for_count+' data-id='+coupon_id+' onclick="receive(this,indexLinkLogin)">领取</p>'+'</div></div>'
                }else{
                    var shop_couponList_2='<p>'+
                            '<span class="user_jifen">'+credit+'积分 </span>'+
                            '<span class='+for_count+' data-id='+coupon_id+' onclick="convert('+credit+','+coupon_id+',indexLinkLogin)">兑换</span>'+
                            '</p>'+'</div></div>'
                }
                $(".jifen_shops").append(shop_couponList_1+shop_couponList_2);
                $(".load-more").hide();
                /*店铺的标签和用户的标签做对比，如果有相同的，让相同的标签高亮*/
                var token = getCookie("token");
                if(token != -1 && token != undefined){
                    var user=res.data.user_info;
                    if(user.category.length>0 || user.kouwei.length>0){
                        var userLabel=$.unique($.merge(user.category,user.kouwei));//合并两个数组
                        $('.' + shop_id).children('span').each(function(i,obj){
                            for(var n=0;n<userLabel.length;n++){
                                if($(obj).attr("data-id")==userLabel[n]){
                                    $(obj).css("color","rgb(0,170,144)")
                                }
                            }
                        });
                    }
                }
            }
            $(".load-more").hide();
            if(data_size > 3){
                $(".no_more").text('下拉刷新加载更多……');
                $(".no_more").show();
                loadControl = true;
            }
        }

    }
    /*根据位置来显示个人发布的优惠券*/
    function get_address() {    //当前位置的经纬度
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                longitude = r.point.lng;
                latitude = r.point.lat;
                page_2=1;
                num=3;
                UserCouponList();
            }
            else {
                alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true})
    }
    function UserCouponList(){
        var url = "/Home/getUserCouponList";
        var arg = {};
        arg.longitude=longitude;
        arg.latitude=latitude;
        arg.page=page_2;
        arg.num=num;
        arg.is_credit=1;
        ajaxJsonp(url, arg, getUserCouponList);
    }
    function getUserCouponList(res) {
        var data = res.data.list;
        size=res.data.count;
        if(size==0){
            $(".user_coupon").append('<div class="noCouponResult">该地区没有个人发布的优惠券信息！</div>');
            $(".load-more").hide();
        }else{
            for (var j = 0; j < data.length; j++) {
                var shop_id = data[j].shop_id;
                var shop_name = data[j].shop_name;
                var image = data[j].image;
                var business_name = data[j].business_name;
                var discount = data[j].discount;
                var coupon_code = data[j].coupon_code;
                var coupon_id = data[j].coupon_id;
                var start_time = data[j].start_time;  //开始时间
                var expired_time = data[j].expired_time;  //结束时间
                var credit = data[j].credit;
                var start_time1=timeChange(start_time).substr(2, 7);
                var expired_time1=timeChange(expired_time).substr(2, 7);
                var coupon_count = data[j].coupon_count;
                var for_count = data[j].for_count;  //表示剩余的数量
                var percent = (for_count / coupon_count) * 100;  //计算未领取的数量的百分比
                var juli_1 = data[j].juli;    //距离
                var juli = null;
                if (juli_1 < 1) {
                    juli = juli_1.substr(2, 4) * 1000 + "m";
                } else if (juli_1 >= 1) {
                    juli = juli_1.substr(0, 4) + "km";
                }
                var labelList = data[j].label_list;
                var shop_couponList_1 = '' +
                        '<div class="index_stores" onclick="linkToSellDetail(' + shop_id + ')">' +
                        '<div class="store_detail">' +
                        '<div><label class="label_8">' + discount + '</label><img src=' + image + '></div>' +
                        '<ul>' +
                        '<li><a><span>' + business_name + '</span><span>(' + shop_name + ')</span></a></li>' +
                        '<li class="'+shop_id+'">'+
                            '<span data-id="'+labelList[0].id+'">'+labelList[0].name+'</span>'+'  '+
                            '<span data-id="'+labelList[1].id+'">'+labelList[1].name+'</span>'+'  '+
                            '<span>'+labelList[2]+'</span>'+'  '+
                            '<span>'+labelList[3]+'</span>'+
                        '</li>'+
                        '<li>' + juli + '</li>' +
                        '<li>' + start_time1 + '-' + expired_time1 + '</li>' +
                        '</ul>' +
                        '</div>' +
                        '<div class="pinjia">' +
                        '<div class="discuss">' +
                        '</div>'
                if (credit == 0) {
                    var shop_couponList_2 = '<p class=' + for_count + ' data-id=' + coupon_code + ' onclick="receive(this,indexLinkLogin)">领取</p>' + '</div></div>'
                } else {
                    var shop_couponList_2 = '<p>' +
                            '<span class="user_jifen">' + credit + '积分 </span>' +
                            '<span class=' + credit + ' data-id=' + coupon_code + ' onclick="convert_2(this,indexLinkLogin)"> 兑换</span>' +
                            '</p>' + '</div></div>'
                }
                $(".user_coupon").append(shop_couponList_1 + shop_couponList_2);
                /*店铺的标签和用户的标签做对比，如果有相同的，让相同的标签高亮*/
                var user=res.data.user_info;
                if(user.length>0){
                    var userLabel=$.unique($.merge(user.category,user.kouwei));//合并两个数组
                    $('.' + shop_id).children('span').each(function(i,obj){
                        for(var n=0;n<userLabel.length;n++){
                            if($(obj).attr("data-id")==userLabel[n]){
                                $(obj).css("color","rgb(0,170,144)")
                            }
                        }
                    });
                }

            }
            $(".load-more").hide();
            if(size > 3){
                loadControl_2 = true;
                $(".no_more").text('下拉刷新加载更多……');
                $(".no_more").show();
            }

        }

    }
    /* 滚动加载 */
    function loadMoreCouponBind(){
        $(window).scroll(function() {
            var scrollHeight = $(window).scrollTop();
            var totalHeight = document.body.clientHeight;
            var viewHeight = $(window).height();
            if(no*page >= data_size) {
                allLoad = true;
                $(".no_more").text('没有更多了……');
                $(".no_more").show();
            }
            if((scrollHeight + viewHeight) >= totalHeight && !allLoad) {
                page++;
                if(loadControl) {
                    loadControl = false;
                    isFirstTime = false;
                    loadingShops();
                }
            }
        })
    }
    function loadMoreCouponBind_2(){
        $(window).scroll(function() {
            var scrollHeight = $(window).scrollTop();
            var totalHeight = document.body.clientHeight;
            var viewHeight = $(window).height();
            if(num*page_2 > size) {
                allLoad_2 = true;
                $(".no_more").text('没有更多了……');
                $(".no_more").show();
            }
            if((scrollHeight + viewHeight) >= totalHeight && !allLoad_2) {
                page_2++;
                if(loadControl_2) {
                    loadControl_2 = false;
                    isFirstTime2 = false;
                    UserCouponList();
                }
            }
        })
    }

</script>
</body>
</html>
